<?php
namespace app\api\controller;
use app\common\model\AddressModel;
use app\common\model\UserModel;
use think\Db;
use think\Validate;

class Address extends Common
{
    public function add_address(){
        $data = $this->checkSign(true);
        $result = AddressModel::add($data);
        return checkRes($result,'添加');
    }
    public function get_address(){
        $data = $this->checkSign(true);
        $result = AddressModel::where('user_id',$data['user_id'])
            ->order('id','desc')
            ->select();
        return package(0,'success',$result);
    }
    public function del_address(){
        $data = $this->checkSign();
        $id = $data['id']??0;
        if(!$id){
            return package(10006,'id错误');
        }
        $result = AddressModel::where('user_id',$data['user_id'])
            ->where('id',$id)
            ->delete();
        return checkRes($result,'删除');
    }
    public function getAddressInfo(){
        $data = $this->checkSign();
        $id = $data['id']??0;
        if(!$id){
            return package(10006,'id错误');
        }
        $info = AddressModel::where('id',$id)->where('user_id',$data['user_id'])->find();
        return package(0,'success',$info);
    }
    public function getMyRegion(){
        $data = $this->checkSign();
        $addModel = new AddressModel();
        $res = Validate::make()
            ->rule([
                'latitude|纬度'=>"require|float",
                'longitude|经度'=>"require|float",
        ]);
        if (!$res->check($data)) {
            return  package('10006',$res->getError());
        }
        $info = $addModel->findRegion($data['latitude'],$data['longitude']);
        if(isset($info['location'])) unset($info['location']);
        return package(0,'获取成功',$info);
    }
    public function getOpenRegion(){
        $this->checkSign();
        $addModel = new AddressModel();
        $list = $addModel->getRegionList(1);
        return package(0,'获取成功',$list);
    }
    //获取回收员地址
    public function getRecyclerLocation(){
        $mtime = config('public.line_time');
        $min5  = date ( "Y-m-d H:i:s" , strtotime ( "-{$mtime} minute" ));
        $where = [['location_time','>',$min5]];
        $list = UserModel::where('user_class',2)
            ->whereNotNull('longitude')
            ->where($where)
            ->field('longitude,latitude,true_name,location_time')
            ->select();
        return package(0,'success',$list);
    }

}